package edu.hm.swe2.shareit.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;

import edu.hm.swe2.shareit.domain.Resource;

public class ResourceDAO {

	private static EntityManager emgr = 
		Persistence.createEntityManagerFactory("ShareItJPA").createEntityManager();

	public void create(Resource entity) {
		emgr.getTransaction().begin();
		emgr.persist(entity);
		emgr.getTransaction().commit();
	}

	public Resource read(int id) {
		return emgr.find(Resource.class, id);
	}

	public void update(Resource entity) {
		emgr.getTransaction().begin();
		emgr.merge(entity);
		emgr.getTransaction().commit();
	}

	public void delete(Resource entity) {
		emgr.getTransaction().begin();
		entity = emgr.merge(entity);
		emgr.remove(entity);
		emgr.getTransaction().commit();
	}

	public List<Resource> findAll() {
		TypedQuery<Resource> tq = emgr.createQuery(
				"select object(r) from Resource r",
				Resource.class);
		return tq.getResultList();

	}
}
